package com.heima.shopweb.controller;

import com.heima.shopweb.model.Cart;
import com.heima.shopweb.model.Item;
import com.heima.shopweb.service.CartService;
import com.heima.shopweb.service.CategoryFeignService;
import com.heima.shopweb.service.GoodFeignService;
import com.heima.shopweb.service.MemberFeignService;
import com.zijie.category.model.Category;
import com.zijie.core.util.JsonResult;
import com.zijie.goods.model.Goods;
import com.zijie.members.model.Members;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/shopping")
public class ShoppingController {
    private GoodFeignService goodFeignService;
    private CategoryFeignService categoryFeignService;
    private CartService cartService;
    private MemberFeignService memberFeignService;

    @Autowired
    public void setGoodFeignService(GoodFeignService goodFeignService) {
        this.goodFeignService = goodFeignService;
    }

    @Autowired
    public void setCategoryFeignService(CategoryFeignService categoryFeignService) {
        this.categoryFeignService = categoryFeignService;
    }

    @Autowired
    public void setCartService(CartService cartService) {
        this.cartService = cartService;
    }

    //进入首页的方法
    @GetMapping("/index")
    public String index(Model model) {
        //查询热门
        ResponseEntity<JsonResult<List<Goods>>> hotByCount = goodFeignService.findAllHot(4);
        JsonResult<List<Goods>> jr = hotByCount.getBody();
        if (jr != null && jr.getCode().equals("200")) {
            List<Goods> goods = jr.getData();
            model.addAttribute("hostItems", goods);
        }
        //查询分类
        ResponseEntity<JsonResult<List<Category>>> tree = categoryFeignService.tree();
        JsonResult<List<Category>> jr1 = tree.getBody();
        if (jr1 != null && jr1.getCode().equals("200")){
            List<Category> categories = jr1.getData();
            model.addAttribute("categories",categories);
        }
        //查询新品
        ResponseEntity<JsonResult<List<Goods>>> newByCount = goodFeignService.findNewByCount(5);
        JsonResult<List<Goods>> jr2 = newByCount.getBody();
        if (jr2 != null && jr2.getCode().equals("200")) {
            List<Goods> newGoods = jr2.getData();
            model.addAttribute("newItems", newGoods);
        }
        return "mall/index";
    }
    //跳转到商品详情页面
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Integer id, Model model) {
        ResponseEntity<JsonResult<Goods>> byId = goodFeignService.findById(id);
        JsonResult<Goods> jr = byId.getBody();
        if (jr != null && jr.getCode().equals("200")) {
            Goods goods = jr.getData();
            model.addAttribute("goods", goods);
        }
        return "mall/detail";
    }
    //购物车页面
    @GetMapping("/cart")
    public String cart(Model model,HttpSession session) {
        //获取当前用户登录的id
        extracted(model, session);
//        System.out.println("items = " + items);
        return "mall/cart";
    }
    @GetMapping("/cart/settle")
    public String settle(Model model,HttpSession session) {
        extracted(model, session);
        Integer memberId = (Integer) session.getAttribute("memberId");
        ResponseEntity<JsonResult<Members>> resultResponseEntity = memberFeignService.findById(memberId);
        JsonResult<Members> jr = resultResponseEntity.getBody();
        if (jr != null && jr.getCode().equals("200")) {
            Members member = jr.getData();
            model.addAttribute("member", member);
        }
        return "mall/order-settle";
    }

    private void extracted(Model model, HttpSession session) {
        Integer memberId = (Integer) session.getAttribute("memberId");
//        System.out.println("memberId = " + memberId);
        //查询当前用户的购物车数据
        List<Cart> carts = cartService.findByMemberId(memberId);
        model.addAttribute("carts", carts);
//        System.out.println("carts = " + carts);
        //根据购物车商品id查询商品
        List<Item> items = new ArrayList<>();
        BigDecimal total = new BigDecimal(0);
        for (Cart cart : carts) {
            Item item = new Item();
            item.setId(cart.getId());
            ResponseEntity<JsonResult<Goods>> byId = goodFeignService.findById(cart.getGoodId());
            JsonResult<Goods> jr = byId.getBody();
//            System.out.println("jr = " + jr);
            if (jr != null && jr.getCode().equals("200")) {
//                System.out.println("goods = " + jr.getData().getName());
                Goods goods = jr.getData();
                item.setNum(cart.getQty());
                item.setName(goods.getName());
                item.setPrice(goods.getPrice());
                item.setPic(goods.getPic());
                total = total.add(item.getPrice().multiply(new BigDecimal(item.getNum())));
                items.add(item);
            }
        }
        model.addAttribute("items", items);
        model.addAttribute("priceTotal", total);
    }

    @PostMapping("/cart")
    @ResponseBody
    public JsonResult<String> addCart(@RequestParam("id") Integer goodId, @RequestParam("number") Integer number, HttpSession session) {
        Integer memberId = (Integer) session.getAttribute("memberId");
        try{
            Cart cart = new Cart();
            cart.setMemberId(memberId);
            cart.setGoodId(goodId);
            cart.setQty(number);
            Cart byCart = cartService.findByCart(cart);
            if(byCart != null){
                return new JsonResult<>("500", "添加失败: 商品已存在", null);
            }
            boolean success = cartService.insert(cart);
            if (success) {
                return new JsonResult<>("200", "保存成功", null);
            }else {
                return new JsonResult<>("500", "保存失败", null);
            }
        }catch (Exception e){
            return new JsonResult<>("500", "保存失败: " + e.getMessage(), null);
        }
    }

    @PostMapping(value = "/cart/updateItem", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public JsonResult<String> updateItem(@RequestParam("itemId") Integer id, @RequestParam("count") Integer count, HttpSession session) {
        try{
            Cart cart = new Cart();
            cart.setId(id);
            cart.setQty(count);
            boolean success = cartService.update(cart);
            System.out.println("success = " + success);
            if (success) {
                return new JsonResult<>("200", "更新成功", null);
            } else {
                return new JsonResult<>("500", "更新失败", null);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult<>("500", "更新失败: " + e.getMessage(), null);
        }

    }

    @PostMapping(value = "/deleteCart", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public JsonResult<String> deleteItem(@RequestParam("itemId") Integer id) {
        try{
            boolean success = cartService.delete(id);
            if (success) {
                return new JsonResult<>("200", "删除成功", null);
            } else {
                return new JsonResult<>("500", "删除失败", null);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult<>("500", "删除失败: " + e.getMessage(), null);
        }
    }

    @Autowired
    public void setMemberFeignService(MemberFeignService memberFeignService) {
        this.memberFeignService = memberFeignService;
    }

}